// Pipeline Component Library Example
// ----------------------------------
// Colin Bowern (colinbowern@hotmail.com)
// January 2007
//
// Copyright (c) 2007 Colin Bowern
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// * The above copyright notice and this permission notice shall be included in
//   all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#region References
using Microsoft.CommerceServer.Inventory;
using Microsoft.CommerceServer.Runtime;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Xml.Serialization;
#endregion

namespace RockstarGuys.PipelineComponents
{
    /// <summary>
    /// Represents a line item on an order form.
    /// </summary>
    /// <remarks>
    /// For more information see http://msdn2.microsoft.com/en-us/library/microsoft.commerceserver.runtime.orders.lineitem.aspx
    /// </remarks>
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1035:ICollectionImplementationsHaveStronglyTypedMembers"), DebuggerDisplay("LineItemId = {LineItemId}")]
    public class LineItem : Dictionary
    {
        #region Fields
        private SimpleListContainer<DiscountApplicationRecord, IDictionary> itemLevelDiscountsApplied;
        private SimpleListContainer<DiscountApplicationRecord, IDictionary> orderLevelDiscountsApplied;
        #endregion

        #region Properties
        #region Identification
        /// <remarks />
        public Guid LineItemId
        {
            get { return GetGuidFromStringValue(LineItem.KeyNames.LineItemId).Value; }
            set { this[LineItem.KeyNames.LineItemId] = value.ToString(); }
        }

        /// <remarks />
        public string ProductCatalog
        {
            get { return this[LineItem.KeyNames.ProductCatalog] as string; }
            set { this[LineItem.KeyNames.ProductCatalog] = value; }
        }

        /// <remarks />
        public string ProductCategory
        {
            get { return this[LineItem.KeyNames.ProductCategory] as string; }
            set { this[LineItem.KeyNames.ProductCategory] = value; }
        }

        /// <remarks />
        public string ProductId
        {
            get { return this[LineItem.KeyNames.ProductId] as string; }
            set { this[LineItem.KeyNames.ProductId] = value; }
        }

        /// <remarks />
        public string ProductVariantId
        {
            get { return this[LineItem.KeyNames.ProductVariantId] as string; }
            set { this[LineItem.KeyNames.ProductVariantId] = value; }
        }
        #endregion

        #region Status
        /// <remarks />
        public bool Delete
        {
            get { return (!(this[LineItem.KeyNames.Delete] == null) && (this.GetValue<string>(LineItem.KeyNames.Delete) == "1")); }
            set { this[LineItem.KeyNames.Delete] = (value ? "1" : null); }
        }

        /// <remarks />
        public string Status
        {
            get { return this[LineItem.KeyNames.Status] as string; }
            set { this[LineItem.KeyNames.Status] = value; }
        }

        /// <remarks />
        public InventoryCondition InventoryCondition
        {
            get { return (InventoryCondition)this[LineItem.KeyNames.InventoryCondition]; }
            set { this[LineItem.KeyNames.InventoryCondition] = (int)value; }
        }
        #endregion

        #region Inventory
        /// <remarks />
        public bool AllowBackordersAndPreorders
        {
            get { return GetValue<bool>(LineItem.KeyNames.AllowBackordersAndPreorders); }
            set { this[LineItem.KeyNames.AllowBackordersAndPreorders] = value; }
        }

        /// <remarks />
        public decimal? InStockQuantity
        {
            get { return GetValue<decimal?>(LineItem.KeyNames.InStockQuantity); }
            set { this[LineItem.KeyNames.InStockQuantity] = (value.HasValue ? (object)value.Value : null); }
        }

        /// <remarks />
        public decimal? PreorderQuantity
        {
            get { return GetValue<decimal?>(LineItem.KeyNames.PreorderQuantity); }
            set { this[LineItem.KeyNames.PreorderQuantity] = (value.HasValue ? (object)value.Value : null); }
        }

        /// <remarks />
        public decimal? BackorderQuantity
        {
            get { return GetValue<decimal?>(LineItem.KeyNames.BackorderQuantity); }
            set { this[LineItem.KeyNames.BackorderQuantity] = (value.HasValue ? (object)value.Value : null); }
        }
        #endregion

        #region Totals
        /// <remarks />
        public decimal Quantity
        {
            get { return GetValue<decimal>(LineItem.KeyNames.Quantity); }
            set { this[LineItem.KeyNames.Quantity] = value; }
        }

        /// <remarks />
        public decimal? PlacedPrice
        {
            get { return GetValue<decimal?>(LineItem.KeyNames.PlacedPrice); }
            set { this[LineItem.KeyNames.PlacedPrice] = (value.HasValue ? new CurrencyWrapper(value.Value) : null); }
        }

        /// <remarks />
        public decimal? ListPrice
        {
            get { return GetValue<decimal?>(LineItem.KeyNames.ListPrice); }
            set { this[LineItem.KeyNames.ListPrice] = (value.HasValue ? new CurrencyWrapper(value.Value) : null); }
        }

        /// <remarks />
        public decimal? LineItemDiscountAmount
        {
            get { return GetValue<decimal?>(LineItem.KeyNames.LineItemDiscountAmount); }
            set { this[LineItem.KeyNames.LineItemDiscountAmount] = (value.HasValue ? new CurrencyWrapper(value.Value) : null); }
        }

        /// <remarks />
        public decimal? OrderLevelDiscountAmount
        {
            get { return GetValue<decimal?>(LineItem.KeyNames.OrderLevelDiscountAmount); }
            set { this[LineItem.KeyNames.OrderLevelDiscountAmount] = (value.HasValue ? new CurrencyWrapper(value.Value) : null); }
        }

        /// <remarks />
        public decimal? ExtendedPrice
        {
            get { return GetValue<decimal?>(LineItem.KeyNames.ExtendedPrice); }
            set { this[LineItem.KeyNames.ExtendedPrice] = (value.HasValue ? new CurrencyWrapper(value.Value) : null); }
        }

        /// <remarks />
        public decimal? TaxTotal
        {
            get { return GetValue<decimal?>(LineItem.KeyNames.TaxTotal); }
            set { this[LineItem.KeyNames.TaxTotal] = (value.HasValue ? new CurrencyWrapper(value.Value) : null); }
        }

        /// <remarks />
        public decimal? TaxIncluded
        {
            get { return GetValue<decimal?>(LineItem.KeyNames.TaxIncluded); }
            set { this[LineItem.KeyNames.TaxIncluded] = (value.HasValue ? new CurrencyWrapper(value.Value) : null); }
        }
        #endregion

        #region Shipping
        /// <remarks />
        public string ShippingAddressId
        {
            get { return this[LineItem.KeyNames.ShippingAddressId] as string; }
            set { this[LineItem.KeyNames.ShippingAddressId] = value; }
        }

        /// <remarks />
        public Guid? ShippingMethodId
        {
            get { return GetGuidFromStringValue(LineItem.KeyNames.ShippingMethodId); }
            set { this[LineItem.KeyNames.ShippingMethodId] = (value.HasValue ? value.Value.ToString() : null); }
        }

        /// <remarks />
        public string ShippingMethodName
        {
            get { return this[LineItem.KeyNames.ShippingMethodName] as string; }
            set { this[LineItem.KeyNames.ShippingMethodName] = value; }
        }
        #endregion

        #region Discounts
        /// <remarks />
        public SimpleListContainer<DiscountApplicationRecord, IDictionary> ItemLevelDiscountsApplied
        {
            get
            {
                if (this.itemLevelDiscountsApplied == null)
                {
                    if (this[LineItem.KeyNames.ItemLevelDiscountsApplied] == null)
                    {
                        this[LineItem.KeyNames.ItemLevelDiscountsApplied] = new SimpleListClass();
                    }
                    this.itemLevelDiscountsApplied = new SimpleListContainer<DiscountApplicationRecord, IDictionary>(this.GetValue<ISimpleList>(LineItem.KeyNames.ItemLevelDiscountsApplied));
                }
                return this.itemLevelDiscountsApplied;
            }
        }

        /// <remarks />
        public SimpleListContainer<DiscountApplicationRecord, IDictionary> OrderLevelDiscountsApplied
        {
            get
            {
                if (this.orderLevelDiscountsApplied == null)
                {
                    if (this[LineItem.KeyNames.ItemLevelDiscountsApplied] == null)
                    {
                        this[LineItem.KeyNames.ItemLevelDiscountsApplied] = new SimpleListClass();
                    }
                    this.orderLevelDiscountsApplied = new SimpleListContainer<DiscountApplicationRecord, IDictionary>(this.GetValue<ISimpleList>(LineItem.KeyNames.OrderLevelDiscountsApplied));
                }
                return this.orderLevelDiscountsApplied;
            }
        }
        #endregion

        #region Product Information
        /// <remarks />
        public string DisplayName
        {
            get { return this[LineItem.KeyNames.CatalogInformation.DisplayName] as string; }
            set { this[LineItem.KeyNames.CatalogInformation.DisplayName] = value; }
        }
        #endregion
        #endregion

        #region Constructor
        /// <summary>
        /// Initializes a new instance of the <see cref="T:LineItem"/> class.
        /// </summary>
        /// <remarks>
        /// The underlying store can be persisted through referencing the InnerList property.
        /// </remarks>
        public LineItem() : this(string.Empty, string.Empty, string.Empty, decimal.Zero) { }

        /// <summary>
        /// Initializes a new instance of the <see cref="T:LineItem"/> class.
        /// </summary>
        /// <param name="container">The container.</param>
        [CLSCompliant(false)]
        public LineItem(IDictionary container) : base(container) { }

        /// <summary>
        /// Initializes a new instance of the <see cref="T:LineItem"/> class.
        /// </summary>
        /// <param name="productCatalog">The product catalog.</param>
        /// <param name="productId">The product id.</param>
        /// <param name="quantity">The quantity.</param>
        public LineItem(string productCatalog, string productId, int quantity)
            : this(productCatalog, productId, null, quantity) { }

        /// <summary>
        /// Initializes a new instance of the <see cref="T:LineItem"/> class.
        /// </summary>
        /// <param name="productCatalog">The product catalog.</param>
        /// <param name="productId">The product id.</param>
        /// <param name="variantId">The variant id.</param>
        /// <param name="quantity">The quantity.</param>
        public LineItem(string productCatalog, string productId, string variantId, decimal quantity)
            : base()
        {
            this.LineItemId = Guid.NewGuid();
            this.ProductCatalog = productCatalog;
            this.ProductCategory = string.Empty;
            this.ProductId = productId;
            this.ProductVariantId = variantId;
            this.Quantity = quantity;

            this.Status = string.Empty;
            this.InventoryCondition = default(InventoryCondition);

            this.AllowBackordersAndPreorders = true;

            this.ShippingAddressId = string.Empty;
            this.ShippingMethodId = Guid.Empty;
            this.ShippingMethodName = string.Empty;

            this.DisplayName = string.Empty;
        }
        #endregion

        #region Nested Types
        /// <summary>
        /// Keys used to access the properties in the dictionary.
        /// </summary>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes")]
        public struct KeyNames
        {
            /// <remarks />
            public const string LineItemId = "index";
            /// <remarks />
            public const string ProductCatalog = "product_catalog";
            /// <remarks />
            public const string ProductCategory = "product_category";
            /// <remarks />
            public const string ProductId = "product_id";
            /// <remarks />
            public const string ProductVariantId = "product_variant_id";
            /// <remarks />
            public const string Delete = "delete";
            /// <remarks />
            public const string Status = "item_status";
            /// <remarks />
            public const string InventoryCondition = "_inventory_condition";
            /// <remarks />
            public const string AllowBackordersAndPreorders = "_inventory_allow_backorder_and_preorder";
            /// <remarks />
            public const string InStockQuantity = "_inventory_in_stock_for_request";
            /// <remarks />
            public const string PreorderQuantity = "_inventory_pre_order_for_request";
            /// <remarks />
            public const string BackorderQuantity = "_inventory_back_order_for_request";
            /// <remarks />
            public const string Quantity = "quantity";
            /// <remarks />
            public const string PlacedPrice = "cy_placed_price";
            /// <remarks />
            public const string ListPrice = "_cy_iadjust_regularprice";
            /// <remarks />
            public const string LineItemDiscountAmount = "_cy_itemlevel_discounts_subtotal";
            /// <remarks />
            public const string OrderLevelDiscountAmount = "_cy_orderlevel_discounts_subtotal";
            /// <remarks />
            public const string ExtendedPrice = "_cy_oadjust_adjustedprice";
            /// <remarks />
            public const string TaxTotal = "_cy_tax_total";
            /// <remarks />
            public const string TaxIncluded = "_cy_tax_included";
            /// <remarks />
            public const string ShippingAddressId = "shipping_address_id";
            /// <remarks />
            public const string ShippingMethodId = "shipping_method_id";
            /// <remarks />
            public const string ShippingMethodName = "shipping_method_name";
            /// <remarks />
            public const string ItemLevelDiscountsApplied = "_itemlevel_discounts_applied";
            /// <remarks />
            public const string OrderLevelDiscountsApplied = "_orderlevel_discounts_applied";
            /// <remarks />
            [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
            public struct CatalogInformation
            {
                /// <remarks />
                public const string DisplayName = "_product_DisplayName";
            }
        }
        #endregion
    }
}
